"""
Case Type   : GSC功能模块
Case Name   : gs_gsc_clean清除指定database缓存
Create At   : 2022/05/10
Owner       : opentestcase024
Description :
    1、打开gsc开关;
    2、重启数据库生效;
    3、创建数据库;
    4、创建表并查询;
    5、查看syscache占用情况;
    5.1、查看gs_gsc_memory_detail占用情况;
    5.2、查看gs_gsc_dbstat_info占用情况;
    5.3、查看gs_gsc_table_detail占用情况;
    5.4、查看gs_gsc_catalog_detail占用情况;
    6、删除指定库缓存信息
    7、查看syscache占用情况;
    7.1、查看gs_gsc_memory_detail占用情况;
    7.2、查看gs_gsc_dbstat_info占用情况;
    7.3、查看gs_gsc_table_detail占用情况;
    7.4、查看gs_gsc_catalog_detail占用情况;
Expect      :
    1、打开gsc开关; 修改成功
    2、重启数据库生效; 重启成功
    3、创建数据库; 创建成功
    4、创建表并查询; 操作成功
    5、查看syscache占用情况; 缓存信息正确
    5.1、查看gs_gsc_memory_detail占用情况; 指定库totalsize结果大于0
    5.2、查看gs_gsc_dbstat_info占用情况; 查询结果包括0库和指定库2条记录，指定库total_memory查询结果大于0
    5.3、查看gs_gsc_table_detail占用情况; 查询结果包括0库和指定库,指定库查询结果大于0
    5.4、查看gs_gsc_catalog_detail占用情况; 查询结果包括0库和指定库,指定库查询结果大于0
    6、删除指定库缓存信息; 删除成功
    7、查看syscache占用情况; 缓存信息正确
    7.1、查看gs_gsc_memory_detail占用情况; 指定库totalsize结果小于步骤5.1
    7.2、查看gs_gsc_dbstat_info占用情况; 查询结果0库、可能存在指定库；指定库total_memory查询结果小于步骤5.2
    7.3、查看gs_gsc_table_detail占用情况; 查询结果0库、可能存在指定库；查询结果小于步骤5.3
    7.4、查看gs_gsc_catalog_detail占用情况; 查询结果0库、可能存在指定库；查询结果小于步骤5.4
History     :
    Modified by peilinqian at 2025/1/21:teardown增加集群主备恢复动作，以防对其他用例产生影响
    modified: 2023/1/29 modified by opentestcase024,进行clean后，后台又快速进行部分缓存，导致步骤7断言失败
        修改7.1至7.4部分步骤及断言结果，保证较步骤5有所减少即可。
"""
import os
import time
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class GscTestCase(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info("----this is setup----")
        self.log.info(f'----{os.path.basename(__file__)}:start----')
        self.db_name = 'db_gsc0038'
        self.tb_name = 'tb_gsc0038'
        self.com = Common()
        self.constant = Constant()
        self.sh = CommonSH('PrimaryDbUser')

        step_txt = '----step0:查看数据库状态是否正常;----'
        self.log.info(step_txt)
        status_result = self.sh.get_db_cluster_status('status')
        self.assertTrue(status_result, '执行失败:' + step_txt)
        step_txt = '----step0:查看enable_global_syscache初始配置值;----'
        self.log.info(step_txt)
        self.init_para1 = self.com.show_param("enable_global_syscache")

    def test_main(self):
        if self.init_para1 == 'off':
            step_txt = '----step1:打开gsc开关; expect:修改成功----'
            self.log.info(step_txt)
            result = self.sh.execute_gsguc('set',
                                           self.constant.GSGUC_SUCCESS_MSG,
                                           f"enable_global_syscache= on")
            self.assertTrue(result, '执行失败:' + step_txt)

            step_txt = '----step2:重启数据库生效; expect:重启成功----'
            self.log.info(step_txt)
            restart = self.sh.restart_db_cluster()
            self.assertTrue(restart, '执行失败:' + step_txt)
            self.is_reset_para = True
        else:
            step_txt = '----gsc开关设置正常，跳过step1、step2----'
            self.log.info(step_txt)
            self.is_reset_para = False

        step_txt = f'----step3:创建数据库; expect:创建成功----'
        self.log.info(step_txt)
        create_db = f'drop database if exists {self.db_name};' \
            f'create database {self.db_name};'
        create_result = self.sh.execut_db_sql(create_db)
        self.log.info(create_result)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, create_result,
                      '执行失败:' + step_txt)

        step_txt = '----step4:创建表并查询; expect:操作成功----'
        self.log.info(step_txt)
        create_tb_sql = f"create table {self.tb_name} " \
            f"(c_integer integer,c_tinyint tinyint," \
            f"c_smallint smallint,c_binary_integer binary_integer," \
            f"c_bigint bigint,c_numeric numeric(10,4)," \
            f"c_number number(10,4),c_smallserial smallserial);" \
            f"select * from {self.tb_name};"
        create_result = self.sh.execut_db_sql(create_tb_sql,
                                              dbname=f'{self.db_name}')
        self.log.info(create_result)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, create_result,
                      '执行失败:' + step_txt)
        self.assertIn('0 rows', create_result, '执行失败:' + step_txt)

        time.sleep(5)

        step_txt = '----step5:查看syscache占用情况; expect:缓存信息正确----'
        self.log.info(step_txt)
        db_oid = f"(select cast((select oid from pg_database where " \
            f"datname = '{self.db_name}') as text))"
        check_sql1 = f"select totalsize from gs_gsc_memory_detail where " \
            f"db_id = ({db_oid});"
        check_sql2 = f"select * from gs_gsc_dbstat_info({db_oid});"
        check_sql2_1 = f"select total_memory from " \
            f"gs_gsc_dbstat_info({db_oid}) where " \
            f"database_name = '{self.db_name}';"
        check_sql3 = f"select * from gs_gsc_table_detail({db_oid});"
        check_sql3_1 = f"select * from gs_gsc_table_detail" \
            f"({db_oid}) where database_name = '{self.db_name}';"
        check_sql4 = f"select * from gs_gsc_catalog_detail({db_oid});"
        check_sql4_1 = f"select * from gs_gsc_catalog_detail" \
            f"({db_oid}) where database_name = '{self.db_name}';"

        step_txt = '----step5.1:查看gs_gsc_memory_detail占用情况; ' \
                   'expect:指定库totalsize结果大于0----'
        self.log.info(step_txt)
        check_result5_1 = self.check_select(check_sql1, False)
        self.assertGreater(check_result5_1, 0, '执行失败:' + step_txt)
        step_txt = '----step5.2:查看gs_gsc_dbstat_info占用情况; ' \
                   'expect:查询结果包括0库和指定库2条记录，指定库total_memory查询结果大于0----'
        self.log.info(step_txt)
        check_result5_2 = self.check_select(check_sql2)
        self.assertEqual(2, check_result5_2, '执行失败:' + step_txt)
        check_result5_2_1 = self.check_select(check_sql2_1, False)
        self.assertGreater(check_result5_2_1, 0, '执行失败:' + step_txt)
        step_txt = '----step5.3:查看gs_gsc_table_detail占用情况; ' \
                   'expect:查询结果包括0库和指定库,指定库查询结果大于0----'
        self.log.info(step_txt)
        check_result5_3 = self.check_select(check_sql3)
        self.assertGreater(check_result5_3, 0, '执行失败:' + step_txt)
        check_result5_3_1 = self.check_select(check_sql3_1)
        self.assertGreater(check_result5_3_1, 0, '执行失败:' + step_txt)
        step_txt = '----step5.4:查看gs_gsc_catalog_detail占用情况; ' \
                   'expect:查询结果包括0库和指定库,指定库查询结果大于0----'
        self.log.info(step_txt)
        check_result5_4 = self.check_select(check_sql4)
        self.assertGreater(check_result5_4, 0, '执行失败:' + step_txt)
        check_result5_4_1 = self.check_select(check_sql4_1)
        self.assertGreater(check_result5_4_1, 0, '执行失败:' + step_txt)

        step_txt = '----step6:删除指定库缓存信息; expect:删除成功----'
        self.log.info(step_txt)
        clean_sql = f"select * from gs_gsc_clean({db_oid});"
        clean_result = self.sh.execut_db_sql(clean_sql)
        self.log.info(clean_result)
        self.assertEqual(clean_result.splitlines()[-2].strip().lower(), 't',
                         '执行失败:' + step_txt)

        step_txt = '----step7:查看syscache占用情况; expect:缓存信息正确----'
        self.log.info(step_txt)
        step_txt = '----step7.1:查看gs_gsc_memory_detail占用情况; ' \
                   'expect:指定库totalsize结果小于步骤5.1----'
        self.log.info(step_txt)
        check_result7_1 = self.check_select(check_sql1)
        self.assertLessEqual(check_result7_1, check_result5_1,
                             '执行失败:' + step_txt)
        step_txt = '----step7.2:查看gs_gsc_dbstat_info占用情况; ' \
                   'expect:查询结果0库、可能存在指定库；指定库total_memory查询结果小于步骤5.2----'
        self.log.info(step_txt)
        check_result7_2 = self.check_select(check_sql2)
        self.assertLessEqual(check_result7_2, 2, '执行失败:' + step_txt)
        check_result7_2_1 = self.check_select(check_sql2_1)
        self.assertLessEqual(check_result7_2_1, check_result5_2_1,
                             '执行失败:' + step_txt)
        step_txt = '----step7.3:查看gs_gsc_table_detail占用情况; ' \
                   'expect:查询结果0库、可能存在指定库；查询结果小于步骤5.3----'
        self.log.info(step_txt)
        check_result7_3 = self.check_select(check_sql3)
        self.assertLess(check_result7_3, check_result5_3, '执行失败:' + step_txt)
        check_result7_3_1 = self.check_select(check_sql3_1)
        self.assertLess(check_result7_3_1, check_result5_3_1,
                        '执行失败:' + step_txt)
        step_txt = '----step7.4:查看gs_gsc_catalog_detail占用情况; ' \
                   'expect:查询结果0库、可能存在指定库；查询结果小于步骤5.4----'
        self.log.info(step_txt)
        check_result7_4 = self.check_select(check_sql4)
        self.assertLess(check_result7_4, check_result5_4, '执行失败:' + step_txt)
        check_result7_4_1 = self.check_select(check_sql4_1)
        self.assertLess(check_result7_4_1, check_result5_4_1,
                        '执行失败:' + step_txt)

    def check_select(self, sql, is_total_count=True):
        """
        :param: sql: 查询对象sql
        :param: is_total_count: 返回结果行数count，还是具体结果
        :return: 查询结果count数，或者查询具体结果
        """
        select_result = self.sh.execut_db_sql(sql)
        self.log.info(select_result)
        if is_total_count:
            return int(select_result.splitlines()[-1].split()[0][1:])
        else:
            if select_result.splitlines()[-2].strip():
                return int(select_result.splitlines()[-2].strip())
            else:
                return 0

    def tearDown(self):
        step_txt = '----this is teardown----'
        self.log.info(step_txt)
        step1_txt = '----清理数据库; expect:清理成功----'
        self.log.info(step1_txt)
        drop_cmd = f"drop database if exists {self.db_name};"
        drop_result = self.sh.execut_db_sql(drop_cmd)
        self.log.info(drop_result)

        if self.is_reset_para:
            self.step2_txt = '----恢复参数为初始值并查询; expect:设置成功----'
            self.log.info(self.step2_txt)
            self.msg1 = self.sh.execute_gsguc('set',
                                              self.constant.GSGUC_SUCCESS_MSG,
                                              f"enable_global_syscache "
                                              f"={self.init_para1}")

            self.step3_txt = '----重启数据库生效; expect:重启成功----'
            self.log.info(self.step3_txt)
            self.restart = self.sh.restart_db_cluster()
            self.step4_txt = '----查询数据库状态; expect:状态正常----'
            self.log.info(self.step4_txt)
            status = self.sh.exec_cm_ctl(mode='query', param='-Cv')
            self.log.info(status)
            p_status = status.splitlines()[-1].split('|')[0].split('6001')[-1]
            if 'Primary' in p_status and "cluster_state   : Normal" in status:
                self.log.info('---集群状态正常，无需恢复为初始状态---')
            else:
                recovery = self.sh.exec_cm_ctl(mode='switchover',
                                                   param='-a')
                self.log.info(recovery)
                time.sleep(10)
            self.status_result = self.sh.get_db_cluster_status('status')

        self.log.info(f'----{os.path.basename(__file__)}:end----')
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_result,
                      "执行失败" + step_txt + step1_txt)
        if self.is_reset_para:
            self.assertTrue(self.msg1, '执行失败:' + self.step2_txt)
            self.assertTrue(self.restart, '执行失败:' + self.step3_txt)
            self.assertTrue(self.status_result, '执行失败:' + self.step4_txt)
